package com.ittable.tdcqfdmeo.serivice.handler;

import com.ittable.tdcqfdmeo.serivice.util.BeanFactoryUtils;
import com.lagou.rpcdemo.request.RpcRequest;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.Method;

/**
 * @author srh
 * @date 2020/10/18
 **/
@Component
public class UserServerHandler extends ChannelInboundHandlerAdapter {

    @Resource
    private BeanFactoryUtils beanFactoryUtils;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        RpcRequest rpcRequest = (RpcRequest) msg;
        Class<?> serviceClass = Class.forName(rpcRequest.getClassName());
        Object service = beanFactoryUtils.getBean(serviceClass);

        String serviceMethodName = rpcRequest.getMethodName();
        Class<?>[] methodParameterTypes = rpcRequest.getParameterTypes();
        Object[] methodParameters = rpcRequest.getParameters();

        Method method = service.getClass().getMethod(serviceMethodName, methodParameterTypes);
        rpcRequest.setResult(method.invoke(service, methodParameters));
        ctx.writeAndFlush(rpcRequest);
    }
}
